﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//添加命名空间引用
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using SerizalClass;
using System.Data.SqlClient;
using ExamDataModel;
using System.Collections;
using System.Configuration;

namespace WebExamServer
{
    public partial class frmServer : Form
    {
        UdpClient udpClient = null;

        Thread loginthread = null;
        Thread send = null;
        SqlConnection conn = null;
        IPAddress serverip = null;
        Sunisoft.IrisSkin.SkinEngine se = null;
        UdpClient udpsend = null;

        public static string sqlconnction = System.Configuration.ConfigurationManager.ConnectionStrings["WebExamServer.Properties.Settings.examDBConnectionString"].ConnectionString;
        public static string sqlconn = Properties.Settings.Default.examDBConnectionString;
        public frmServer()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            udpClient = new UdpClient(8000);//考试端口

            se = new Sunisoft.IrisSkin.SkinEngine();
            se.SkinAllForm = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            skinEngine1.SkinFile = @"skin\SteelBlack.ssk";
            button2.Enabled = false;
            button3.Enabled = false;

            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)//获取考试服务器的ip地址
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    serverip = _IPAddress;
                }
            }
            this.Text = serverip.ToString();
            send = new Thread(new ThreadStart(sendiptoclient));
            send.IsBackground = true;
            send.Start();
        }
        public void sendiptoclient()//广播线程, 告诉局域网内考试端，服务器的IP和考试通信端口号
        {
            ServerIP sip = new ServerIP(serverip, 8000);//实例化一个服务器对象，包含了服务器的IP地址和考试端口
            byte[] bData = new SeriClass().SerializeBinary(sip).ToArray();
            udpsend = new UdpClient();
            while (true)
            {
                IPEndPoint iep = null;
                try
                {
                    iep = new IPEndPoint(IPAddress.Broadcast, 10000);
                    udpsend.Send(bData, bData.Length, iep);
                }
                catch
                {
                    break;
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            loginthread = new Thread(new ThreadStart(listenlogin));
            loginthread.IsBackground = true;
            loginthread.Start();
            button2.Enabled = true;
            button3.Enabled = true;

        }
        Kaosheng ks = null;
        private void listenlogin()
        {
            IPEndPoint iep = null;
            while (true)
            {
                byte[] bytes = udpClient.Receive(ref iep);
                ks = new SeriClass().DeSerializeBinary(new MemoryStream(bytes)) as Kaosheng;
                switch (ks.Cmd)
                {
                    #region  //登录处理
                    case 1:
                        {
                            try
                            {
                                conn = new SqlConnection(sqlconn);
                                conn.Open();

                                string sql = "select * from student where zkz='" + ks.Zkz + "' and state='未登录'";
                                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                                DataSet ds = new DataSet();
                                da.Fill(ds);
                                bool login = true;
                                if (ds.Tables[0].Rows.Count != 0)
                                {
                                    ks.Xh = ds.Tables[0].Rows[0]["xh"].ToString();
                                    ks.Xm = ds.Tables[0].Rows[0]["xm"].ToString();
                                    ks.Bj = ds.Tables[0].Rows[0]["bj"].ToString();
                                    ks.Cmd = 1;
                                    login = false;
                                }
                                else//不存在该考生
                                {
                                    ks.Xh = "";
                                    ks.Xm = "";
                                    ks.Bj = "";
                                    ks.Cmd = 0;//0没有这个考生
                                }
                                if (login == false)
                                {
                                    string sql1 = "update student set state='已登录',ip='" + iep.Address + "'  where zkz='" + ks.Zkz + "'";
                                    SqlCommand sc = new SqlCommand(sql1, conn);
                                    sc.ExecuteNonQuery();
                                }
                                byte[] bData = new SeriClass().SerializeBinary(ks).ToArray();
                                udpClient.Send(bData, bData.Length, iep);
                                break;
                            }
                            catch(Exception ex)
                            {
                                ks.Xh = "";
                                ks.Xm = "";
                                ks.Bj = "";
                                ks.Cmd = -1;//-1服务器出现错误
                                byte[] bData = new SeriClass().SerializeBinary(ks).ToArray();
                                udpClient.Send(bData, bData.Length, iep);
                            }
                            finally
                            {
                                conn.Close();
                            }
                            break;
                        }
                    #endregion
                    #region  //抽题处理
                    case 2:
                        {
                            try
                            {
                                conn = new SqlConnection(sqlconnction);
                                conn.Open();
                                string sql = "select * from  tk";
                                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                                DataSet ds = new DataSet();
                                da.Fill(ds);
                                List<TK> Tm = new List<TK>();
                                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                {
                                    int th = Convert.ToInt32(ds.Tables[0].Rows[i]["th"]);
                                    string tmnr = ds.Tables[0].Rows[i]["tmnr"].ToString();
                                    string tmzj = ds.Tables[0].Rows[i]["tmzj"].ToString();
                                    string answer1 = ds.Tables[0].Rows[i]["answer1"].ToString();
                                    string answer2 = ds.Tables[0].Rows[i]["answer2"].ToString();
                                    string answer3 = ds.Tables[0].Rows[i]["answer3"].ToString();
                                    string answer4 = ds.Tables[0].Rows[i]["answer4"].ToString();
                                    string result = ds.Tables[0].Rows[i]["result"].ToString();
                                    TK record = new TK(th, tmnr, tmzj, answer1, answer2, answer3, answer4, result);
                                    Tm.Add(record);
                                }
                                byte[] bData = new SeriClass().SerializeBinary(Tm).ToArray();
                                udpClient.Send(bData, bData.Length, iep);
                                break;
                            }
                            catch
                            {
                            }
                            finally
                            {
                                conn.Close();
                            }
                            break;
                        }
                    #endregion
                    #region  //考试结果处理
                    case 3:
                        {
                            try
                            {
                                conn = new SqlConnection(sqlconnction);
                                conn.Open();
                                for (int i = 0; i < ks.Result.Count; i++)
                                {
                                    string sql = "insert into ksresult(zkz,ktxh,tkth,xsanswer,tkanswer) values('";
                                    sql += ks.Result[i].Zkz + "','";
                                    sql += Convert.ToInt32(ks.Result[i].Ktxh) + "','";
                                    sql += Convert.ToInt32(ks.Result[i].Tkth) + "','";
                                    sql += ks.Result[i].Xsanswer + "','";
                                    sql += ks.Result[i].Tkanswer + "')";
                                    SqlCommand da = new SqlCommand(sql, conn);
                                    da.ExecuteNonQuery();
                                }
                                byte[] bData = Encoding.UTF8.GetBytes("交卷成功！");
                                udpClient.Send(bData, bData.Length, iep);
                                break;
                            }
                            catch
                            {
                                byte[] bData = Encoding.UTF8.GetBytes("交卷失败，请重新提交！");
                                udpClient.Send(bData, bData.Length, iep);

                            }
                            finally
                            {
                                conn.Close();
                            }
                            break;
                        }
                    default:
                        break;
                        #endregion
                }
            }
        }

        private void frmServer_FormClosing(object sender, FormClosingEventArgs e)
        {
            //终止线程
            if (loginthread != null) loginthread.Abort();
        }

        private void button3_Click(object sender, EventArgs e)
        {

            KsMonitor f = new KsMonitor(serverip);
            f.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Gaijuan f = new Gaijuan(serverip);
            f.Show();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (udpsend != null)
                udpsend.Close();
            Application.Exit();
        }
    }
}